package userService

import (
	"chart.zozoo.net/app/dao/userDao"
	"chart.zozoo.net/app/models"
	"chart.zozoo.net/core/mysql"
	"errors"
	"github.com/google/uuid"
	"gorm.io/gorm"
)

type RegisterParams struct {
	UserName string `json:"username" binding:"required,min=3,max=32"`
	Password string `json:"password" binding:"required,min=3,max=32"`
}

func (r *RegisterParams) Register() (id int, err error) {
	u := &models.Users{
		Username: r.UserName,
		Password: r.Password,
	}

	//查询用户数是否存在
	res := mysql.MysqlClient.Select("id").
		Where("username = ?", r.UserName).
		First(u)
	if res.Error != nil && !errors.Is(res.Error, gorm.ErrRecordNotFound) {
		return 0, err
	}
	if u.Id > 0 {
		return 0, errors.New("用户名冲突")
	}

	//加密密码
	u.Password, err = u.HashPwd(u.Password)
	if err != nil {
		return 0, err
	}

	//生成uuid
	u.Uuid = uuid.New().String()

	//创建用户
	err = userDao.Create(u)
	if err != nil {
		return
	}

	return u.Id, nil
}
